<template>
  <div class="register">
    <!-- 顶部导航区域 -->
    <nav-bar>
      <template v-slot:center>
        <span style="font-size: 0.16rem; color: #fff">新用户注册</span>
      </template>
    </nav-bar>
    <van-image width="100" height="100" src="https://img01.yzcdn.cn/vant/cat.jpeg" class="img-icon" round />
    <van-form @submit="onSubmit">
      <van-field
        v-model="name"
        name="name"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="password_confirmation"
        type="password"
        name="password_confirmation"
        label="确认密码"
        placeholder="确认密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="email"
        type="email"
        name="email"
        label="电子邮箱"
        placeholder="电子邮箱"
        :rules="[{ required: true, message: '请填写电子邮箱' }]"
      />
      <router-link to="/login" class="link">已有账号?去登陆</router-link>

      <div style="margin: 16px">
        <van-button round block native-type="submit" class="btn">注册</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { toRefs, reactive } from 'vue'
import { Notify, Toast } from 'vant'
import { register } from 'network/user'
import { useRouter } from 'vue-router'
export default {
  name: 'Register',
  setup(props) {
    const router = useRouter()
    // 用户信息
    let userInfo = reactive({
      name: '',
      password: '',
      password_confirmation: '',
      email: ''
    })
    function onSubmit(value) {
      // 先验证...
      if (userInfo.password !== userInfo.password_confirmation)
        return Notify({ type: 'danger', message: '两次密码不一致' })

      // 提交给服务器
      register(value).then(res => {
        if (res.status === 201) {
          Toast.success('注册成功')
          // 注册成功后一秒跳转到注册页面
          setTimeout(() => {
            router.push('/login')
          }, 1000)
          // 清空用户的信息
          userInfo.name = ''
          userInfo.password = ''
          userInfo.password_confirmation = ''
          userInfo.email = ''
        }
      })
    }
    return {
      ...toRefs(userInfo),
      onSubmit
    }
  }
}
</script>

<style lang="scss" scoped>
.register {
  width: 100vw;
  .img-icon {
    margin: 0.2rem auto;
    display: block;
  }
  .btn {
    background: #42b983 !important;
    color: white;
  }
  .link {
    padding: 0.2rem 0 0 0.2rem;
    display: block;
    color: #42b983;
  }
}
</style>